package logic

import (
	"context"
	"net"
	"time"

	"probe-tools/internal/svc"
	"probe-tools/pb/probe"

	"github.com/zeromicro/go-zero/core/logx"
)

type TcpProbeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTcpProbeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TcpProbeLogic {
	return &TcpProbeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TcpProbeLogic) TcpProbe(in *probe.TcpProbeRequest) (*probe.TcpProbeResponse, error) {
	start := time.Now()
	timeout := time.Duration(in.Timeout) * time.Second
	if in.Timeout <= 0 {
		timeout = 5 * time.Second // 默认超时5秒
	}

	// 尝试建立TCP连接
	conn, err := net.DialTimeout("tcp", in.Address, timeout)
	if err != nil {
		return &probe.TcpProbeResponse{
			Success:  false,
			Duration: time.Since(start).Milliseconds(),
			Error:    err.Error(),
		}, nil
	}
	defer conn.Close()

	return &probe.TcpProbeResponse{
		Success:  true,
		Duration: time.Since(start).Milliseconds(),
		Type:     "tcp",
	}, nil
}
